package com.suieqian.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Excel 工具类
 *
 * @author 芋道源码
 */
public class ExcelUtils {

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response  响应
     * @param filename  文件名
     * @param sheetName Excel sheet 名
     * @param head      Excel head 头
     * @param data      数据列表哦
     * @param <T>       泛型，保证 head 和 data 类型的一致性
     * @throws IOException 写入失败的情况
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 Class<T> head, List<T> data) throws Exception {
        EasyExcel.write(getOutputStream(filename, response), head)
                .sheet(sheetName)
                .doWrite(data);
    }

    /**
     * 导出文件时为Writer生成OutputStream
     *
     * @param fileName
     * @param response
     * @return
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }


    public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
        // autoCloseStream(false) 不要自动关闭，交给 Servlet 自己处理
        return EasyExcel.read(file.getInputStream(), head, null)
                .autoCloseStream(false)
                .doReadAllSync();
    }

    /**
     * 无模型读（默认读取sheet0,从第2行开始读）
     *
     * @param file
     * @return
     */
    public static List<Map<Integer, String>> read(MultipartFile file) throws IOException {
        return EasyExcelFactory.read(file.getInputStream()).sheet().doReadSync();
    }
}
